package cn.com.isfree.db;

import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;
import org.tio.utils.json.Json;
import org.tio.utils.lock.SetWithLock;

import com.alibaba.fastjson.JSON;

import cn.com.isfree.tio.TioUil;
import cn.com.isfree.tio.common.Const;
import cn.com.isfree.tio.common.ShowcasePacket;
import cn.com.isfree.tio.common.Type;
import cn.com.isfree.tio.common.packets.SyncReqBody;
import cn.com.isfree.tio.common.packets.SyncRespBody;

@SpringBootApplication
public class App implements CommandLineRunner{
	
	@Value("${tio.server.ip}")
	private String serverIp;
	@Value("${tio.server.port}")
	private int serverPort;
	
	@Override
	public void run(String... args) throws Exception {
		try {
			TioUil.initTio(serverIp, serverPort);
			int i = 0;
			while(true) {
				i++;
				try {
					SetWithLock<ChannelContext> setWithLock = TioUil.serverGroupContext.users.find(TioUil.serverGroupContext, "root");
					if(setWithLock!=null) {
						Set<ChannelContext> set = setWithLock.getObj();
						if(set!=null) {
							for (ChannelContext channelContext : set) {
								if(channelContext!=null&&!channelContext.isClosed()) {
									int inc = TioUil.getSynSeqAtomicLong();
									SyncReqBody syncReqBody = new SyncReqBody();
									syncReqBody.setText("stop");
									syncReqBody.setSynSeq(inc);
									ShowcasePacket respPacket = new ShowcasePacket();
									respPacket.setType(Type.SYNC_MSG_REQ);
									respPacket.setSynSeq(inc);
									respPacket.setBody(Json.toJson(syncReqBody).getBytes(ShowcasePacket.CHARSET));
									ShowcasePacket packet = (ShowcasePacket) Aio.synSend(channelContext, respPacket,3000);
									String jsonStr = null;
									SyncRespBody bsBody = null;
									if (packet.getBody() != null) {
										jsonStr = new String(packet.getBody(), Const.CHARSET);
										bsBody = Json.toBean(jsonStr, SyncRespBody.class);
									}
									System.out.println("同步拿到的数据:" + JSON.toJSONString(bsBody));
								}
							}
						}
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
				Thread.sleep(1000);
			}
		}catch (Exception e) {
			e.printStackTrace();
			TioUil.serverStop();
		}
	}
	
	public static void main(String[] args) {
		SpringApplication app = new SpringApplication(App.class);
		app.run(args);
	}
}
    